from fastapi import FastAPI, Depends, HTTPException, Response, Query, Request,File, UploadFile  
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional
import os
import asyncio
import logging
import uvicorn
app = FastAPI(title="M First API", version="0.1")

access = None

class LoginPayLoad(BaseModel):
    username: str
    password: str
    type:Optional[str]

@app.post("/api/login/account")
async def login_account(payload: LoginPayLoad):
    await asyncio.sleep(2)    
    logging.debug(payload.username)
    print(payload)
    print(payload.password)
    print(payload.username)
    print(payload.password == "ant.design")
    if payload.password == 'ant.design':
        print("....")
        if payload.username == "admin":
            print("xxxxx")
            access = "admin"
            return {"status": "ok", "type": payload.type, "currentAuthority": "admin"}
        elif payload.username == "user":
            access = "user"
            return {"status": "ok", "type": payload.type, "currentAuthority": "user"}
    
    if payload.type == 'mobile':
        access = 'admin'
        return {"status": "ok", "type": payload.type, "currentAuthority": "admin"}
    
    raise HTTPException(status_code=401, detail={"status": "error", "type": payload.type, "currentAuthority": "guest"})


@app.post("/api/login/outLogin")
async def logout(request: Request):
    print(request.url)
    access = ''
    return {"data": {}, "success": True}
def get_access():
    # 请实现 get_access 函数，用于判断用户是否有访问权限
    return 'admin'
    

@app.get("/api/currentUser")
async def get_current_user():
    access = get_access()
    if not access:
        return {
            "success": True,
            "data": {
                "isLogin": False,
            },
            "errorCode": "401",
            "errorMessage": "请先登录！",
        }
    
    return {
        "success": True,
        "data": {
            "name": "Serati Ma",
            "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png",
            "userid": "00000001",
            "email": "antdesign@alipay.com",
            "signature": "海纳百川，有容乃大",
            "title": "交互专家",
            "group": "蚂蚁金服－某某某事业群－某某平台部－某某技术部－UED",
            "tags": [
                {"key": "0", "label": "很有想法的"},
                {"key": "1", "label": "专注设计"},
                {"key": "2", "label": "辣~"},
                {"key": "3", "label": "大长腿"},
                {"key": "4", "label": "川妹子"},
                {"key": "5", "label": "海纳百川"},
            ],
            "notifyCount": 12,
            "unreadCount": 11,
            "country": "China",
            "access": access,
            "geographic": {
                "province": {"label": "浙江省", "key": "330000"},
                "city": {"label": "杭州市", "key": "330100"},
            },
            "address": "西湖区工专路 77 号",
            "phone": "0752-268888888",
        },
    }

# 挂载静态文件的服务，让返回的video_url能正常访问
app.mount("/public", StaticFiles(directory="./public"), name="public")
async def save_video(file: UploadFile):
    # 获取文件临时路径
    tmp_path = file.file

    # 指定保存目录并确保存在
    VIDEO_UPLOAD_DIR = "./public/videos/"
    if not os.path.exists(VIDEO_UPLOAD_DIR):
        os.makedirs(VIDEO_UPLOAD_DIR)

    # 定义要保存的文件名和完整路径
    file_name = file.filename
    save_path = os.path.join(VIDEO_UPLOAD_DIR, file_name)

    try:
        # 将上传的文件保存到服务器指定目录
        with open(save_path, "wb") as buffer:
            while content := await file.read(1024):
                buffer.write(content)
        
        # 返回视频文件的URL供前端预览播放
        video_url = "http://127.0.0.1:8090/public/videos/" + file_name
        return {"video_url": video_url}
    except Exception as e:
        return {"error": f"Failed to save the video: {str(e)}"}

@app.post("/api/upload-video")
async def upload_video(video_file: UploadFile = File(...)):
    try:
        print(video_file)
        print("......")
        result = await save_video(video_file)
        return result
    except Exception as e:
        return {"error": f"An error occurred during processing: {str(e)}"}




class ResponseData(BaseModel):
    id: int
    title: str
    video_url: str

class ListResponse(BaseModel):
    list: List[ResponseData]
    total: int

class ApiResponse(BaseModel):
    code: int
    message: str
    data: ListResponse

@app.get("/api/video-list", response_model=ApiResponse)
async def get_video_list():
    # 示例数据，实际情况下可能是从数据库查询得到的结果
    videos = [
        {"id": 1, "title": "dali", "video_url": "http://127.0.0.1:8090/public/videos/motion.mp4"},
        {"id": 2, "title": "dali", "video_url": "http://127.0.0.1:8090/public/videos/motion.mp4"}
    ]

    # 构造ListResponse对象
    list_response = ListResponse(
        list=[ResponseData(**video) for video in videos],
        total=len(videos),
    )

    # 返回最终的ApiResponse对象
    return ApiResponse(code=0, message="OK", data=list_response)

# 获取请求的基础信息
@app.get("/base-info")
async def get_base_info(request: Request):
    # 获取客户端IP地址（可能需要通过中间件解析代理头以正确获取）
    client_ip = request.client.host
    # 获取请求方法，如GET、POST等
    method = request.method
    # 获取完整的请求URL
    url = request.url
    # 获取请求的headers
    headers = dict(request.headers)
    
    # AWS Lambda环境下的Request ID可以通过特定方式获取，但FastAPI本身并不直接提供
    # 如果使用了AWS Lambda与API Gateway集成，可能需要从事件(event)中获取Request ID
    # 例如，如果是Lambda Proxy Integration，可以从event['requestContext']['requestId']中获取
    
    return {"client_ip": client_ip, "method": method, "url": str(url), "headers": headers}

# 如果需要访问请求体数据（对于POST, PUT等方法）
@app.post("/body-data")
async def post_body_data(request: Request):
    # 获取请求体内容（假设是JSON格式）
    body = await request.body()
    # 转换成字节串
    body_content = body.decode("utf-8")
    # 或者如果知道是JSON，则可以直接解析
    json_body = await request.json()
    
    return {"body": body_content, "json_body": json_body}

__name__ = "hello"
if __name__ == "__main__":
    # 运行：uvicorn hello:app --reload --port 8090
    uvicorn.run(app, host="127.0.0.1", port=8090)